<template>
  <el-table :data="formData[props.config.id]" stripe class="table-container" :class="config.attributes?.cssClass" v-show="!config.attributes.hidden"
    :border="config.attributes.border" :stripe="config.attributes.stripe" :fit="config.attributes.fit"
    :max-height="config.attributes.maxHeight">
    <el-table-column fixed="left" label="#" type="index" align="center" />
    <el-table-column v-for="column in config.children" :key="column.id" :label="getColumnInfo(column, 'label', '未命名')"
      :width="getColumnInfo(column, 'width', 'auto')" :align="getColumnInfo(column, 'columnAlign', 'left')"
      :fixed="getColumnInfo(column, 'columnFixed', false)">
      <template #default="{ row, $index }">
        <div v-if="$index >= 0"><!-- 不知道是什么bug 会有一个-1行 导致规则判断出错 -->
          <component v-for="child in column.children" :row-index="$index" :parent-id="config.id" :key="child.id"
            :is="designer.renderComponent(child)" :config="child" />
        </div>
      </template>
    </el-table-column>
    <el-table-column align="center" fixed="right" width="120"
      v-if="!formConfig.disabled && !config.attributes.disabled">
      <template #header>
        <el-button link :icon="Plus" type="primary" @click="addSubFormData({})">新增</el-button>
      </template>
      <template #default="{ row, $index }">
        <el-button link :icon="Delete" type="danger" @click="delSubFormData($index)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
</template>

<script setup>
import { inject, onMounted } from 'vue'
import { Plus, Delete } from '@element-plus/icons-vue';
import { executeEventHandler } from '@/utils/eventExecutor'

const designer = inject('designer')
const formData = inject('formData')
const widgetList = inject('widgetList')
const formConfig = inject('formConfig')

const props = defineProps({
  config: {
    type: Object,
    required: true
  }
})

const getColumnInfo = (column, field, fallback) => {
  const first = column.children?.[0]
  return first?.attributes?.[field] ?? fallback
}

const addSubFormData = (data) => {
  formData.value[props.config.id].push(data)
}

const delSubFormData = (index) => {
  formData.value[props.config.id].splice(index, 1)
}

onMounted(() => {
  if (!Array.isArray(formData.value[props.config.id])) {
    formData.value[props.config.id] = []
  }
  executeEventHandler(props.config.events?.onMounted, { widgetConfig: props.config, formData: formData.value, widgetList: widgetList.value, tableData: formData.value[props.config.id], addSubFormData, delSubFormData })
});
</script>

<style scoped>
.table-container {
  width: 100%;
  margin: 5px 0;
}
</style>